package nio.Bchannel;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author 帅小伙
 * @date 2022/1/14
 * @description
 * 复制文件
 */
public class FileChannel03 {

    public static void main(String[] args) throws Exception {
        // 获取读写channel
        File file = new File("file1.txt");
        FileInputStream fileInputStream = new FileInputStream(file);
        FileChannel fileInputStreamChannel = fileInputStream.getChannel();

        File file1 = new File("file2.txt");
        FileOutputStream fileOutputStream = new FileOutputStream(file1);
        FileChannel fileOutputStreamChannel = fileOutputStream.getChannel();

        ByteBuffer buffer = ByteBuffer.allocate(512);

        while(true) {
            // 关键属性重置
            buffer.clear();
            int read = fileInputStreamChannel.read(buffer);
            if(read == -1) break;
            buffer.flip();
            fileOutputStreamChannel.write(buffer);
        }


        fileInputStream.close();
        fileOutputStream.close();

    }
}
